/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.processor;

import com.seari.bean.BaseClient;
import io.netty.channel.Channel;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * @author Rainbow
 */
public class ChannelChecker implements Runnable
{
    BaseClient client;
    int count;
    static final int MAX_RETRY_TIME = 5; //5次判断channel为非活跃状态时，进行重连
    static final int RETRY_INTERVAL = 2; //断连重试间隔，单位：秒
    protected static Logger logger = LoggerFactory.getLogger(ChannelChecker.class);
    
    public ChannelChecker(BaseClient client)
    {
        this.client = client;
    }

    @Override
    public void run()
    {
        while (true)
        {   
            Channel channel = client.getChannel();         
            boolean flag = false;
            if(null != channel)
            {
                flag = channel.isActive();
            }
            if(!flag)//channel连接未成功
            {
                count++;
                if(count > MAX_RETRY_TIME)
                {
                    try
                    {
                        count = 0; //重置失败计数器
                        logger.debug("reset client");
                        client.reset();
                    } catch (Exception ex)
                    {
                        logger.warn(ex.getMessage());
                        ex.printStackTrace();
                        continue;
                    }
                }
            }else{ //channel连接成功，重置失败计数
                count = 0;
            }
            try
            {
                TimeUnit.SECONDS.sleep(RETRY_INTERVAL);
            } catch (InterruptedException ex)
            {
                logger.warn(ex.getMessage());
            }
        }
    }
    
}
